import {ObjectDirective} from "vue";
// pnpm install --save @types/element-resize-detector && pnpm install element-resize-detector
// @ts-ignore
import elementResize from "element-resize-detector";
import {DirectiveBinding, VNode} from "@vue/runtime-core";
// 创建实例 使用超快的基于滚动的方法
// @ts-ignore
const elListen: elementResizeDetectorMaker.Erd = elementResize({
    strategy: "scroll",
    callOnAdd: true
})

export interface BindValue {
    func: (funcParams: any) => void;
    funcParams: any;
    /**
     * 是否立即执行一次
     */
    immediate: boolean;
}

export const ElementResize: ObjectDirective = {
    mounted(el, binding: DirectiveBinding, vnode: VNode, prevVNode) {
        let bindValue: BindValue = binding.value
        if (bindValue.immediate) {
            bindValue.func(bindValue.funcParams)
        }
        elListen.listenTo(el, bindValue.func)
    },
    beforeUnmount(el, binding: DirectiveBinding, vnode: VNode, prevVNode) {
        elListen.uninstall(el)
    }
}